package com.sun.showcase.es;

import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TestServiceImpl implements TestService {

    @Autowired
    TestRepository testRepository;

    @Override
    public void save(TestDomain domain) {
        testRepository.save(domain);
    }

    @Override
    public void deleteById(String id) {
        testRepository.deleteById(id);
    }

    @Override
    public void update(TestDomain domain) {
        testRepository.save(domain);
    }

    @Override
    public Page<TestDomain> select(TestDomain domain) {
        // 构建查询条件
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        // 添加基本的分词查询
        if(StringUtils.isNotEmpty(domain.getName())){
            queryBuilder.withQuery(QueryBuilders.termQuery("name", domain.getName()));
        }
//        if(domain.getAge() != null){
//            queryBuilder.withQuery(QueryBuilders.queryStringQuery());
//        }
        return testRepository.search(queryBuilder.build());
    }
}
